package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifyCodeController {
    @Autowired
    private RedisService redisService;
    @RequestMapping("initVerifyCode")
    private void initVerifyCode(String uuid, HttpServletResponse response){
        String exp = VerifyCodeImgUtil.generateVerifyCode();
        Integer ret = VerifyCodeImgUtil.calc(exp);
        //把计算的结果存到redis里
        redisService.set(SeckillKeyPrefix.VERIFYCODE_RESULT,uuid,ret);
        //创建验证码
        BufferedImage verifyCodeImg = VerifyCodeImgUtil.createVerifyCodeImg(exp);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(verifyCodeImg,"jpg",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
